<template>
  <div>
    <!--编辑地址-->
    <Modal width="60%" class-name="vertical-center-modal" class="pop-address" :mask-closable="false"
      @on-cancel="hidePop" v-model="showPop"
      :title="formValidate.id ? $t('user.editShippingAddress') : $t('user.addedShippingAddress')">
      <div class="pop-address-content">
        <Form v-if="showPop" ref="formValidate" :label-width="100" :model="formValidate" :rules="ruleValidate">
          <div class="flex-content">
            <Row :gutter="8">
              <Col span="12">
              <FormItem :label="$t('user.name')" prop="name">
                <Input v-model="formValidate.name" :placeholder="$t('personal.FirstName')"></Input>
              </FormItem>
              </Col>
              <Col span="12">
              <FormItem prop="surname" :label-width="0">
                <Input class="input" v-model="formValidate.surname" :placeholder="$t('personal.LastName')"></Input>
              </FormItem>
              </Col>
            </Row>
          </div>
          <div class="flex-content">
            <!--国家-->
            <Row :gutter="8">
              <Col span="9">
              <FormItem :label="$t('user.locationAddress')" prop="countryCode">
                <Select v-model="formValidate.countryCode" @on-change="onCountry" class="select" filterable>
                  <Avatar v-if="currentCountryImage" :src="currentCountryImage" slot="prefix" size="small" />
                  <Option v-for="item in countryList" :value="item.code" :label="item.text" :key="item.id">
                    <div class="option-content">
                      <img v-if="item.flagImg" class="logo" :src="item.flagImg" alt="" />
                      <span>{{ item.text }}</span>
                    </div>
                  </Option>
                </Select>
              </FormItem>
              </Col>
              <Col span="5">
              <FormItem :label-width="0" prop="provinceCode">
                <Select :disabled="!formValidate.countryCode" :label-in-value="true" @on-change="onSelectProvince"
                  v-model="formValidate.provinceCode" :placeholder="$t('user.pleaseSelect')">
                  <Option v-for="item in provinceList" :value="item.pid" :key="item.id">
                    {{ item.nameLocal }}
                  </Option>
                </Select>
              </FormItem>
              </Col>
              <Col span="5">
              <FormItem :label-width="0" :prop="cityList.length == 0 ? '' : 'cityCode'">
                <Select :disabled="!formValidate.provinceCode || cityList.length == 0" :label-in-value="true"
                  @on-change="onSelectCity" v-model="formValidate.cityCode" :placeholder="$t('user.pleaseSelect')">
                  <Option v-for="item in cityList" :value="item.id" :key="item.id">
                    {{ item.nameLocal }}
                  </Option>
                </Select>
              </FormItem>
              </Col>
              <Col span="5">
              <Input class="input" :disabled="!formValidate.cityCode" v-model="formValidate.areaText"
                :placeholder="$t('user.area')"></Input>
              </Col>
            </Row>
          </div>
          <!--详细地址-->
          <FormItem :label="$t('user.detailedAddress')" prop="addressDetail">
            <Input v-model="formValidate.addressDetail" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              :placeholder="$t('user.enterFullShippingAddress')"></Input>
          </FormItem>
          <!--邮编-->
          <FormItem :label="$t('user.postcode')" prop="postalCode">
            <Input v-model="formValidate.postalCode" placeholder=""></Input>
          </FormItem>
          <!--手机号-->
          <FormItem :label="$t('user.mobile')" prop="mobile">
            <!--            <Input v-model="formValidate.mobile" placeholder=""></Input>-->
            <Row :gutter="8">
              <Col span="8">
              <!--国际区号-->
              <Select :label-in-value="true" v-model="formValidate.regionCodeCountry"
                :placeholder="$t('user.pleaseSelect')" @on-change="regionChange">
                <Option v-for="(item, index) in regionCodeList" :label="item.text"
                  :value="item.code + item.regionCountry" :key="item.code + index">
                  <div class="region-code">
                    <img class="region-code-icon" :src="item.flagImg" alt="" />
                    <span>{{ item.text }}</span>
                  </div>
                </Option>
              </Select>
              </Col>
              <Col span="16">
              <Input v-model="formValidate.mobile" placeholder=""></Input>
              </Col>
            </Row>
          </FormItem>
          <!--                  <FormItem :label="$t('user.addressTag')">-->
          <!--                    <Input v-model="formValidate.townText" placeholder=""></Input>-->
          <!--                  </FormItem>-->
          <!--                  <FormItem v-if="" :label="$t('user.tag')">-->
          <!--                    <RadioGroup v-model="formValidate.gender">-->
          <!--                      <Radio label="male">{{$t('user.home')}}</Radio>-->
          <!--                      <Radio label="female">{{$t('user.professional')}}</Radio>-->
          <!--                    </RadioGroup>-->
          <!--                  </FormItem>-->
          <FormItem :label="$t('user.defaultAddress')">
            <i-switch v-model="formValidate.isDefault" size="large"></i-switch>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button @click="hidePop">{{ $t("user.cancel") }}</Button>
        <Button :loading="loading" v-if="formValidate.id" @click="onAddressEdit" type="primary">{{ $t("user.edit")
          }}</Button>
        <Button :loading="loading" v-else @click="onAddressAdd" type="primary">{{ $t("user.confirm") }}</Button>
      </div>
    </Modal>
    <!--选择地址弹窗-->
    <Modal width="60%" class-name="vertical-center-modal" class="pop-address" v-model="selectAddressPop"
      :title="$t('submitParcel.selectAddress')">
      <div class="user-addr">
        <div class="content">
          <!--地址列表-->
          <div class="table-wrap">
            <div class="table">
              <div class="table-header">
                <Row>
                  <Col span="6">
                  <div class="th">{{ $t("submitParcel.addressee") }}</div>
                  </Col>
                  <Col span="14">
                  <div class="th">{{ $t("submitParcel.detailedAddress") }}</div>
                  </Col>
                  <Col span="4">
                  <div class="th">{{ $t("submitParcel.operation") }}</div>
                  </Col>
                </Row>
              </div>
              <div class="table-content">
                <Row v-for="(item, index) in userAddressList" :key="index" class="table-tr tr-active">
                  <Col span="6">
                  <div class="td">{{ item.recipientName.split(",")[0] }} {{ item.recipientName.split(",")[1] }}</div>
                  </Col>
                  <Col span="14">
                  <div class="td">
                    <div>{{ item.postalCode }} +{{ item.regionCode }} {{ item.mobile }}</div>
                    <div>{{ item.addressDetail }} {{ item.areaText ? item.areaText + "," : "" }}{{ item.cityText ?
                      item.cityText + "," : "" }}{{ item.provinceText }},{{ item.countryText }}</div>
                    <div class="tag">
                      {{ item.townText }}
                    </div>
                  </div>
                  </Col>
                  <Col span="4">
                  <div class="td fun">
                    <Button @click="onSelect(item)">{{ $t("submitParcel.selectAddress") }}</Button>
                  </div>
                  </Col>
                </Row>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { countryAddressList, cityApiList } from "@/api/administrativedivisions";
import { addressAdd, addressEdit, addressList, deleteAddress } from "@/api/address";
import { pointUser } from "@/common/point/api-hook";//打点日志
export default {
  data() {
    return {
      showPop: false,
      selectAddressPop: false,
      userAddressList: [],
      loading: false,
      ruleValidate: {
        name: [
          { required: true, message: this.$t("user.pleaseEnter") + this.$t("user.name"), trigger: "blur" },
          { type: 'string', max: 17, message: this.$t('ruleValidate.name'), trigger: 'change' }
        ],
        surname: [
          { required: true, message: this.$t("user.pleaseEnter") + this.$t("personal.LastName"), trigger: "blur" },
          { type: 'string', max: 17, message: this.$t('ruleValidate.name'), trigger: 'change' }
        ],
        addressDetail: [{ required: true, message: this.$t("ruleValidate.address_tip"), trigger: "blur" }],
        postalCode: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.postcode"), trigger: "blur" }],
        mobile: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.mobile"), trigger: "blur" }],
        countryCode: [{ required: true, message: this.$t("user.InputAddress"), trigger: "change" }],
        provinceCode: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.province"), trigger: "change" }],
        cityCode: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.city"), trigger: "change" }],
      },
      formValidate: {
        id: "",
        surname: "", // 姓
        name: "", // 名
        addressDetail: "", // 街道地址，详细地址
        areaCode: "", // 区code
        areaText: "", // 区文本
        cityCode: "", // 市code
        cityText: "", // 市文本
        countryCode: "", // 国家编码
        districtCode: "", // 地址编码
        regionCode: "", // 手机国际区号
        regionCodeCountry: "", // 区号+国家
        regionCountry: '', // 区号国家
        isDefault: false, // 是否默认地址
        mobile: "", // 手机号
        phone: "", // 电话
        postalCode: "", // 邮政编码
        provinceCode: "",
        provinceText: "", // 省份文本
        recipientName: "", // 收件人姓名
        townText: "", // 文本
      },
      currentCountryImage: "", // 当前国家图片
      cityList: [], // 市区列表
      provinceList: [],
      orderEditType: true, // 如果这个状态是true, 那么当执行编辑保存的时候执行新增方法，如果是false说明已经修改过，就执行编辑方法
    }
  },
  computed: {
    ...mapState({
      countryList: (state) => {
        let list = [];
        if (state.config.config) {
          list = state.config.config.countryList;
        }
        return list;
      },
      regionCodeList: (state) => {
        // 国际区号
        let list = [];
        if (state.config.config) {
          list = state.config.config.regionCodeList;
        }
        return list;
      },
    }),
  },
  methods: {
    open() {
      this.showPop = true
    },
    openSelect() {
      this.selectAddressPop = true;
    },
    // 选择了地址
    onSelect(addInfo) {
      if (this.orderEditType) {
        this.orderEditType = false;
      }
      this.currentAddr = addInfo;
      this.currentAddr.name = addInfo.recipientName.split(",")[0];
      this.currentAddr.surname = addInfo.recipientName.split(",")[1];
      this.selectAddressPop = false;
      this.$emit("on-change", this.currentAddr);
    },
    // 获取地址信息列表
    getAddressList() {
      // 获取地址列表
      addressList().then((res) => {
        let arr = res.result.filter((item) => {
          return item.isDefault == true;
        })
        // isDefault 有默认地址
        if (arr.length > 0) {
          this.currentAddr = arr[0];
          this.currentAddr.name = arr[0].recipientName.split(',')[0];
          this.currentAddr.surname = arr[0].recipientName.split(',')[1];
          this.$emit('on-change', this.currentAddr);
        } else {
          // 没默认地址的情况下取接口返回的第一条
          if (res.result.length > 0) {
            this.currentAddr = res.result[0];
            this.currentAddr.name = res.result[0].recipientName.split(',')[0];
            this.currentAddr.surname = res.result[0].recipientName.split(',')[1];
            this.$emit('on-change', this.currentAddr);
          }
        }
        this.userAddressList = res.result;
      });
    },
    onCountry(value) {
      this.gloabalLoading = true;
      // 选择国家
      let info = this.countryList.find((item) => {
        return item.code == value;
      });
      this.formValidate.countryText = info.text;
      this.currentCountryImage = info.flagImg;
      this.formValidate.provinceCode = "";
      this.formValidate.cityCode = "";
      this.formValidate.areaCode = "";
      this.formValidate.provinceText = "";
      this.formValidate.cityText = "";
      this.formValidate.areaText = "";
      this.onCountryAddressList(info.code, "provinceList");
    },
    onCountryAddressList(code, type) {
      // 获取
      this[type] = [];
      countryAddressList(code)
        .then((res) => {
          this[type] = res.result;
          this.gloabalLoading = false;
        })
        .catch(() => {
          this.gloabalLoading = false;
        });
    },
    onSelectProvince(info) {
      // 选择省份
      this.getCityList(info.value, "cityList");
      this.formValidate.provinceText = info.label;
      this.formValidate.cityCode = "";
      this.formValidate.areaCode = "";
      this.formValidate.cityText = "";
      this.formValidate.areaText = "";
    },
    getCityList(code, type) {
      // 获取
      this[type] = [];
      cityApiList(code)
        .then((res) => {
          this[type] = res.result;
          this.gloabalLoading = false;
        })
        .catch(() => {
          this.gloabalLoading = false;
        });
    },
    onSelectCity(info) {
      this.cityList.forEach((item) => {
        if (item.id == info.value) {
          this.formValidate.postalCode = item.postalCode;
        }
      })
      // 选择市
      this.formValidate.cityText = info.label;
      this.formValidate.areaCode = "";
      this.formValidate.areaText = "";
    },
    // 区号赋值
    regionChange(item) {
      let selectedOption = this.regionCodeList.find((option) => option.code + option.regionCountry === item.value);
      this.formValidate.regionCode = selectedOption.code || "";
      this.formValidate.regionCountry = selectedOption.regionCountry || "";
    },
    hidePop() {
      // 隐藏弹窗
      this.showPop = false;
      this.setFormValidate();
    },
    onAddressEdit() {
      // 编辑地址
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          if (!this.formValidate.countryCode || !this.formValidate.provinceCode || (!this.formValidate.cityCode && this.cityList.length > 0)) {
            this.$Message.error(this.$t("user.InputAddress"));
            return;
          }
          if (!this.formValidate.surname) {
            this.$Message.error(this.$t("user.pleaseEnter") + this.$t("user.surname"));
            return;
          }
          if (!this.formValidate.regionCode) {
            this.$Message.error(this.$t("user.pleaseSelect") + this.$t("user.mobileAreaCode"));
            return;
          }
          // if (this.orderEditType) {
          //   this.onAddressAdd(true);
          //   return false;
          // }
          this.loading = true;
          this.formValidate.recipientName = `${this.formValidate.name},${this.formValidate.surname}`;
          addressEdit(this.formValidate)
            .then((res) => {
              this.$Message.success(this.$t("submitParcel.changeSuccessfully"));
              this.loading = false;
              this.showPop = false;
              this.currentAddr = { ...this.currentAddr, ...this.formValidate };
              this.getAddressList();
              this.setFormValidate();
            })
            .catch(() => {
              this.loading = false;
              this.setFormValidate();
            });
        }
      });
    },
    onAddressAdd() {
      // 添加地址
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          if (!this.formValidate.countryCode || !this.formValidate.provinceCode || (!this.formValidate.cityCode && this.cityList.length > 0)) {
            this.$Message.error(this.$t("user.InputAddress"));
            return;
          }
          if (!this.formValidate.surname) {
            this.$Message.error(this.$t("user.pleaseEnter") + this.$t("personal.LastName"));
            return;
          }
          if (!this.formValidate.regionCode) {
            this.$Message.error(this.$t("user.pleaseSelect") + this.$t("user.mobileAreaCode"));
            return;
          }

          this.loading = true;
          this.formValidate.recipientName = `${this.formValidate.name},${this.formValidate.surname}`;
          addressAdd(this.formValidate)
            .then((res) => {
              pointUser('actions', '2008');
              this.$Message.success(this.$t("user.addSuccessfully"));
              this.loading = false;
              this.showPop = false;
              this.getAddressList();
              this.setFormValidate();
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
  }
}
</script>
<style lang="less" scoped>
.user-addr {
  height: 300px;
  overflow-y: auto;

  .top {
    .num {
      margin-left: 6px;
      color: @t-text-color;
    }
  }

  .content {
    padding-bottom: 24px;

    .table-wrap {
      .table {
        &-header {
          padding: 12px;
          background: @t-table-header-bg;

          .th {
            color: @t-title-color;
            font-size: 14px;
            font-weight: 600;

            .all {
              cursor: pointer;
            }
          }
        }

        &-content {
          border-top: 1px solid @t-table-border-color;

          .table-tr {
            padding: 12px;
            border-bottom: 1px solid @t-table-border-color;
            color: @t-text-color;
            font-size: 14px;

            .fun {
              span {
                margin-right: 24px;
                color: @t-title-color;
                cursor: pointer;
              }

              .tag {
                border-radius: 4px;
                background: @primary-color;
                color: #ffffff;
                padding: 2px 4px;
              }
            }
          }
        }
      }
    }

    .page {
      text-align: right;
      margin-top: 24px;
    }
  }
}

.pop-address {
  .pop-address-content {
    .region-code {
      display: flex;
      align-items: center;

      .region-code-icon {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        overflow: hidden;
        margin-right: 2px;
      }
    }

    .flex-content {
      .input {}

      .select {
        .option-content {
          display: flex;
          align-items: center;

          .logo {
            display: inline-block;
            width: 30px;
            margin-right: 4px;
          }
        }

        :deep(.ivu-select-input) {
          width: auto !important;
        }
      }

      .country-wrap {
        background-color: #fff;
        border-radius: 4px;
        border: 1px solid #dcdee2;
        padding: 0 8px;
      }
    }
  }
}
</style>
